package com.ctgu.ImageRecognition.util;

import com.ctgu.ImageRecognition.vo.ResultVO;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.UUID;

/**
 * ClassName: QiniuUploadUtils
 * Description:
 * date: 2023/7/10 14:49
 *
 * @author 吴杰
 * @since JDK 1.8.0_31
 */
public class QiniuUploadUtils {
    //设置好账号的ACCESS_KEY和SECRET_KEY;这两个登录七牛账号里面可以找到--密钥
    static String ACCESS_KEY = "8xbTPJRtN1zm4GUOodwaGbM5H9wWa4ZufyUvoter";
    static String SECRET_KEY = "zqY0SWVg9y4HbIB6wspoPENa5ESyFdUgJmUu9lqM";
    //要上传的空间;对应到七牛上（自己建文件夹 注意设置公开）
    static String bucketname = "123img";
    //上传文件的路径 ;本地要上传文件路径
    //  String FilePath = "C:\\Users\\Administrator\\Pictures\\good\\g1002\\g100201.jpg";
    //七牛云服务器存储空间的域名
    static String yuName = "http://rxk8l95n8.hn-bkt.clouddn.com/";
    //密钥配置rtmjxv21t.hn-bkt.clouddn.com
    static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    //创建地区zone
    public  static Configuration cfg = new Configuration(Zone.zone2());

    //创建上传对象  Zone.zone2()表示为华南地区   0-4  华东  华北  华南  北美  东南亚
    static UploadManager uploadManager = new UploadManager(cfg);
    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public static String getUpToken(){
        return auth.uploadToken(bucketname);
    }


    //实现图片的上传
    public static ResultVO uploadImage(MultipartFile file) {
//        HashMap<String,Object> returnMap = new HashMap<>();
        try {
            //1.重新生成文件的名称-不重复的
            String newName = UUID.randomUUID().toString().replace("-", "");
            //200b4b6ced284daaaca89ba6ff0f85ae.png
            //2.获取原文件的后缀 .png
            String oldName = file.getOriginalFilename();
            String suffix = oldName.substring(oldName.lastIndexOf("."));
            //3.拼接成新的文件的名字
            String newFileName = newName + suffix;
            //4.实现文件上传
            //put(文件的字节数组,文件名,tolen验证)
            uploadManager.put(file.getBytes(), newFileName, getUpToken());
            //5.返回域名+图片名，让前端能够显示
//            returnMap.put("url",yuName + newFileName);
//            returnMap.put("fileNmae",newFileName);
            return ResultUtil.success("图片上传成功", yuName + newFileName);
        } catch (Exception e) {
            return ResultUtil.fail("图片上传失败！", null);
        }
    }

    public static ResultVO  delete(String key){
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            String deleteKey = key.substring(yuName.length());
            bucketManager.delete("123img", deleteKey);
            return ResultUtil.success("删除成功",null);
        } catch (Exception ex) {
            return ResultUtil.fail("删除失败",null);
        }
    }

}